package controller;

import bean.Student;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import service.StudentService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author HLF
 * @version V1.0
 * @package controller
 * @date 2021/10/25 19:09
 */
public class RegistServlet extends BaseServlet {

    protected void regist(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Integer id = Integer.valueOf(req.getParameter("id"));
        String name = req.getParameter("name");
        String email = req.getParameter("email");
        Integer age = Integer.valueOf(req.getParameter("age"));

        //获取spring容器对象
        WebApplicationContext webApplicationContext =
                WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
        System.out.println(webApplicationContext);
        //获取service对象并执行“注册”的业务方法
        StudentService service = (StudentService) webApplicationContext.getBean("studentService");
        Student student = new Student();
        student.setId(id);
        student.setName(name);
        student.setAge(age);
        student.setEmail(email);
        int i = service.registStudent(student);
        if (i > 0) {
            req.getRequestDispatcher("/pages/registSuccess.jsp").forward(req, resp);
        } else {
            req.getRequestDispatcher("/pages/registFailure.jsp").forward(req, resp);
        }
    }
}
